package mail;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "FileUploadServlet")

public class FileUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //上传文件的准备
        //1.路径
        String webroot=this.getServletContext().getRealPath("/");//外部域的根目录
        System.out.println("当前web应用的目录："+webroot);
        File temppath=new File(webroot+"tmp");
        File uploadpath=new File(webroot+"upload");
        //没有则自动创建
        if(!temppath.exists()){
            temppath.mkdirs();
        }
        if(!uploadpath.exists()){
            uploadpath.mkdirs();
        }
        //2.文件的处理
        //2.1文件大小
        //2.2拿到输入流后的写入，普通的io
        //文件名的问题，是否覆盖，时间戳
        //缓冲区的大小，临时目录
        DiskFileItemFactory factory=new DiskFileItemFactory(1024*1024,temppath);
        ServletFileUpload upload=new ServletFileUpload(factory);
        upload.setFileSizeMax(1024*1024*100);//文件大小限制
        ProgressListener progressListener=new ProgressListener() {
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("到现在为止，"+pBytesRead/1024+"kb已上传，总大小为："
                        +pContentLength/1024+"kb");
                //如果要在前台获取当前上传进度
                //把文件上传进度信息放到session里
                request.getSession().setAttribute("progress",pBytesRead/pContentLength);
            }
        };
        upload.setProgressListener(progressListener);
        upload.setHeaderEncoding("utf-8");//中文
        try{
            List<FileItem> fileItems=upload.parseRequest(request);
            Iterator<FileItem> it=fileItems.iterator();//迭代器
            String from=null;
            String to=null;
            String content=null;
            String subject=null;
            String host=null;
            String pwd=null;
            List<String> files=new ArrayList<>();
            while(it.hasNext()){//遍历
                FileItem fi=it.next();
                if(fi.isFormField()){//是表单
                    System.out.println("字段名："+fi.getFieldName());
                    System.out.println("字段值："+fi.getString("utf-8"));
                    if(fi.getFieldName().equals("to"))
                        to=fi.getString();
                    if(fi.getFieldName().equals("from"))
                        from=fi.getString();
                    if(fi.getFieldName().equals("content"))
                        content=fi.getString();
                    if(fi.getFieldName().equals("subject"))
                        subject=fi.getString();
                    if(fi.getFieldName().equals("host"))
                        host=fi.getString();
                    if(fi.getFieldName().equals("pwd"))
                        pwd=fi.getString();
                }
                else{//是文件
                    InputStream in=fi.getInputStream();
                    FileOutputStream out=new FileOutputStream(new File(
                            uploadpath,fi.getName()));
                    byte buffer[]=new byte[1024];
                    int len=0;
                    while((len=in.read(buffer))>0){
                        out.write(buffer,0,len);
                        /*try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }*/
                    }
                    in.close();
                    out.close();
                    fi.delete();//删除临时文件，必须在流关闭后删除
                    String filename=fi.getName();
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("text/html");
                    response.getWriter().println(filename+"上传成功");
                    files.add(uploadpath+File.separator+filename);
                }
            }
            if(MailHelper.sendEmail(host,from,pwd,to,subject,content,files))
                response.sendRedirect("message.jsp");
        }catch (FileUploadException e){
            response.getWriter().write(e.toString());
        }
    }
}
